package com.apps.ftapp.activity;

import android.app.ProgressDialog;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;

import com.apps.ftapp.R;
import com.apps.ftapp.util.Constant;
import com.apps.ftapp.util.L;
import com.duobeiyun.util.EncryptUtils;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 多贝云直播
 */
public class DuoBActivity extends BaseActivity {


    @BindView(R.id.video_fullView)
    FrameLayout video_fullView;
    @BindView(R.id.webView)
    WebView webView;
    private View xCustomView;
    private WebChromeClient.CustomViewCallback xCustomViewCallback;
    private myWebChromeClient xwebchromeclient;
    private ProgressDialog waitdialog = null;
    private String title;
    private String type;
    String appKey;
    String nickname;
    String partner;
    String roomId;
    String userRole = "2";
    String sign;
    String baseUrl = "http://api.duobeiyun.com/api/v3/room/enter?";

    String url;


    String timestamp = String.valueOf(System.currentTimeMillis());


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_duo_b);
        ButterKnife.bind(this);

        //新页面接收数据
        Bundle bundle = this.getIntent().getExtras();
        roomId = bundle.getString("roomId");
        type = bundle.getString("type");
        title = bundle.getString("title");


        L.i("main", ":::" + roomId + ">>" + type + ">>>" + title + "：：：：：" + Constant.uid);
        setTitle(title);

        commTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                xwebchromeclient.onShowCustomView(webView);
            }
        });

        waitdialog = new ProgressDialog(this);
        waitdialog.setTitle("提示");
        waitdialog.setMessage("视频页面加载中...");
        waitdialog.setIndeterminate(true);
        waitdialog.setCancelable(true);
        waitdialog.show();

//        DuobeiYunClient client = new DuobeiYunClient();
//        L.i("main","client::::"+client.toString());
//        String result = client.generateRoomEnterUrl(
//                java.util.UUID.randomUUID().toString(), // uid
//                "testStudent",                          // nickname
//                "jzf243856e3949455894c5ce48bfee6163", // roomId
//                DuobeiYunClient.ROLE_STUDENT,         // userRole
//                DuobeiYunClient.DEVICE_TYPE_PC        //deviceType
//        );
//        System.out.println(result);
//        System.out.println(result);

        this.partner = Constant.PID;
        this.appKey = Constant.APPKEY;
        this.nickname = "我爱为师";
        generateUrl();
        L.i("main", "url:::::" + url);

        initView(url);

//        initPlayerAndSetCallback();

    }


    public void generateUrl() {
        StringBuffer sb = new StringBuffer();
        sb.append("nickname=").append(this.nickname)
                .append("&")
                .append("partner=")
                .append(this.partner)
                .append("&").append("roomId=")
                .append(this.roomId).append("&")
                .append("timestamp=").append(this.timestamp)
                .append("&").append("uid=")
                .append(Constant.uid).append("&").append("userRole=").append(this.userRole);
        String pMD5Str = sb.toString() + this.appKey;
        this.sign = EncryptUtils.MD5(pMD5Str);
        this.url = this.baseUrl + sb.append("&").append("sign=").append(this.sign).toString();
    }


    private void initView(String url) {


        WebSettings ws = webView.getSettings();
        ws.setBuiltInZoomControls(true);// 隐藏缩放按钮

        ws.setUseWideViewPort(true);// 可任意比例缩放
        ws.setLoadWithOverviewMode(true);// setUseWideViewPort方法设置webview推荐使用的窗口。setLoadWithOverviewMode方法是设置webview加载的页面的模式。

        ws.setSavePassword(true);
        ws.setSaveFormData(true);// 保存表单数据
        ws.setJavaScriptEnabled(true);
        ws.setGeolocationEnabled(true);// 启用地理定位
//        ws.setGeolocationDatabasePath("/data/data/org.itri.html5webview/databases/");// 设置定位的数据库路径
        ws.setDomStorageEnabled(true);
        ws.setSupportMultipleWindows(true);// 新加
        xwebchromeclient = new myWebChromeClient();
        webView.setWebChromeClient(xwebchromeclient);
        webView.setWebViewClient(new myWebViewClient());
        webView.loadUrl(url);

    }


    public class myWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return false;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            waitdialog.dismiss();
        }
    }


    public class myWebChromeClient extends WebChromeClient {
        private View xprogressvideo;

        // 播放网络视频时全屏会被调用的方法
        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            webView.setVisibility(View.INVISIBLE);
            // 如果一个视图已经存在，那么立刻终止并新建一个
            if (xCustomView != null) {
                callback.onCustomViewHidden();
                return;
            }
            video_fullView.addView(view);
            xCustomView = view;
            xCustomViewCallback = callback;
            video_fullView.setVisibility(View.VISIBLE);
        }

        // 视频播放退出全屏会被调用的
        @Override
        public void onHideCustomView() {
            if (xCustomView == null)// 不是全屏播放状态
                return;

            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            xCustomView.setVisibility(View.GONE);
            video_fullView.removeView(xCustomView);
            xCustomView = null;
            video_fullView.setVisibility(View.GONE);
            xCustomViewCallback.onCustomViewHidden();
            webView.setVisibility(View.VISIBLE);
        }

        // 视频加载时进程loading
        @Override
        public View getVideoLoadingProgressView() {
            if (xprogressvideo == null) {
                LayoutInflater inflater = LayoutInflater
                        .from(DuoBActivity.this);
                xprogressvideo = inflater.inflate(
                        R.layout.video_loading_progress, null);
            }
            return xprogressvideo;
        }


        @Override
        public Bitmap getDefaultVideoPoster() {
            if (DuoBActivity.this == null) {
                return null;
            }

            return BitmapFactory.decodeResource(getApplicationContext().getResources(),
                    R.drawable.analysis_choose_right_d);
        }
    }

    /**
     * 判断是否是全屏
     *
     * @return
     */
    public boolean inCustomView() {
        return (xCustomView != null);
    }

    /**
     * 全屏时按返加键执行退出全屏方法
     */
    public void hideCustomView() {
        xwebchromeclient.onHideCustomView();
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }


    @Override
    protected void onResume() {
        super.onResume();
        super.onResume();
        webView.onResume();
        webView.resumeTimers();

        /**
         * 设置为横屏
         */
        if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        webView.onPause();
        webView.pauseTimers();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        super.onDestroy();
        video_fullView.removeAllViews();
        webView.loadUrl("about:blank");
        webView.stopLoading();
        webView.setWebChromeClient(null);
        webView.setWebViewClient(null);
        webView.destroy();
        webView = null;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (inCustomView()) {
                // webViewDetails.loadUrl("about:blank");
                hideCustomView();
                return true;
            } else {
                webView.loadUrl("about:blank");
//                DuoBActivity.this.finish();
            }
        }
        return false;
    }

}
